from django.shortcuts import render
import json
from data import models
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from wechatpy.utils import WeChatSigner
from wechat_api import Timer
import logging

# Create your views here.
TOKEN = 'buptcampuscard'


@csrf_exempt
def syn_course(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            course_info = re['COURSE_INFO']
            for each in course_info:
                course_id = each['COURSE_ID']
                course_name = each['COURSE_NAME']
                try:
                    course = models.Course.objects.get(id=course_id)
                    course.name = course_name
                    course.save()
                except:
                    course = models.Course(id=course_id, name=course_name)
                    course.save()
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)

    return HttpResponseBadRequest()


@csrf_exempt
def syn_student(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            student_info = re['STUDENT_INFO']
            for each in student_info:
                student_id = each['STUDENT_ID']
                student_name = each['STUDENT_NAME']
                try:
                    student = models.StudentInfo.objects.get(id=student_id)
                    student.name = student_name
                    student.save()
                except:
                    student = models.StudentInfo(id=student_id, name=student_name)
                    student.save()
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)
    return HttpResponseBadRequest()


@csrf_exempt
def syn_news(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            news_list = re['NEWS']
            for each in news_list:
                id = each['NEWS_ID']
                title = each['NEWS_TITLE']
                author = each['NEWS_AUTHOR']
                category = each['NEWS_CATEGORY']
                pub_date = each['NEWS_PUB_DATE']
                content = each['NEWS_CONTENT']
                try:
                    models.News.objects.get(id=id)
                    pass
                except:
                    news = models.News(
                        id=id,
                        title=title,
                        author=author,
                        category=category,
                        pub_date=pub_date,
                        content=content,
                    )
                    news.save()
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)
    return HttpResponseBadRequest()


@csrf_exempt
def syn_bookinfo(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            book_info = re['BOOK_INFO']
            for each in book_info:
                try:
                    book = models.BookInfo.objects.get(id=each['id'])
                    book = models.BookInfo(**each)
                    book.save()
                except models.BookInfo.DoesNotExist:
                    models.BookInfo(**each).save()
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)
    return HttpResponseBadRequest()



@csrf_exempt
def syn_ecard_record(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            try:
                record = re['SAVE_RECORD']
                for each in record:
                    try:
                        cur_stu = models.StudentInfo.objects.get(id=each['student_id'])
                        item = models.Update_item.objects.first()
                        item.record_save_id = each['id']
                        item.save()
                        each.pop('student_id')
                        each.pop('id')
                        models.EcardRecord(student=cur_stu, type=0, **each).save()
                    except:
                        pass
            except:
                record = re['CONSUME_RECORD']
                for each in record:
                    try:
                        cur_stu = models.StudentInfo.objects.get(id=each['student_id'])
                        item = models.Update_item.objects.first()
                        item.record_consume_id = each['id']
                        item.save()
                        each.pop('student_id')
                        each.pop('id')
                        models.EcardRecord(student=cur_stu, type=1, **each).save()
                    except:
                        pass
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)
    return HttpResponseBadRequest()


@csrf_exempt
def syn_course_selection(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            selection = re['COURSE_SELECTION']
            for each in selection:
                try:
                    cur_stu = models.StudentInfo.objects.get(id=each['student_id'])
                    cur_course = models.Course.objects.get(id=each['course_id'])
                    each.pop('student_id')
                    each.pop('course_id')
                    models.CourseSelect(student=cur_stu, course=cur_course, **each).save()
                except:
                    pass
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit()}
        return JsonResponse(response)
    return HttpResponseBadRequest()


@csrf_exempt
def syn_book_lend(req):
    if req.method == 'POST':
        t = Timer()
        t.start()
        re = json.loads(req.body.decode('utf-8'))
        if re['TOKEN'] == TOKEN:
            lend_info = re['BOOK_LEND']
            logging.debug('start')
            for each in lend_info:
                try:
                    cur_stu = models.StudentInfo.objects.get(id=each['student_id'])
                    cur_book = models.BookInfo.objects.filter(name=each['book_name']).first()
                    each.pop('student_id')
                    each.pop('book_name')
                    models.BookLend(student=cur_stu, book=cur_book, **each).save()
                except:
                    pass
        t.end()
        logging.debug(t.timeit())
        response = {'time': t.timeit() + 0.1}
        return JsonResponse(response)
    return HttpResponseBadRequest()


def latest(req):
    if req.method == 'GET':
        if req.GET['TOKEN'] == TOKEN:
            try:
                key = req.GET['KEY']
            except KeyError:
                return HttpResponse(None)
            if key == 'save_record':
                response = models.Update_item.objects.first().record_save_id
            elif key == 'consume_record':
                response = models.Update_item.objects.first().record_consume_id
            else:
                response = 0
            return HttpResponse(response)


def data_del(req):
    if req.method == 'GET':
        if req.GET['TOKEN'] == TOKEN:
            try:
                key = req.GET['KEY']
            except KeyError:
                return HttpResponse('删除失败')
            if key == 'course_selection':
                models.CourseSelect.objects.all().delete()
                return HttpResponse('选课信息删除成功')
            elif key == 'book_lend':
                models.BookLend.objects.all().delete()
                return HttpResponse('图书信息删除成功')
        return HttpResponse('删除失败')
